﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace LeMigue.Framework.Utils
{
    public static class DIUnity
    {
        //TODO: tratar exceções que podem ocorrer

        private static IUnityContainer _unityContainer = null;

        private static IUnityContainer UnityContainer
        {
            get {
                if (_unityContainer == null)
                    throw new Exception("Container di não inicializado");

                return _unityContainer;
            }
        }


        public static void Init(params string[] containers)
        {
            Object thisLock = new Object();

            lock (thisLock)
            {
                _unityContainer = new UnityContainer();

                UnityConfigurationSection section
                    = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

                foreach (string container in containers)
                {
                    ContainerElement contElement = section.Containers.SingleOrDefault(c => c.Name == container);
                    if(contElement != null)
                        section.Configure(_unityContainer, container);
                }

            }
           

        }

        public static T GetInstance<T>(String regName)
        {
            T instance;

            //caso não encontre o registro
            ContainerRegistration registro = UnityContainer.Registrations.SingleOrDefault(r => r.Name == regName);
            if (registro == null)
                throw new Exception("Não encotnrou o registro"); //TODO: criar exceção própria
            else
                instance = UnityContainer.Resolve<T>(regName);

            return instance;
        }
        public static T GetInstance<T>(String regName, Type padrao)
        {
            
            T instance;
            
            //caso não encontre o registro
            ContainerRegistration registro = UnityContainer.Registrations.SingleOrDefault(r => r.Name == regName);
            if(registro == null)
                instance = (T)UnityContainer.Resolve(padrao);
            else
                instance = UnityContainer.Resolve<T>(regName);

            return instance;
        }
    }
}
